#ifndef TOST_CONFIG_CPP
#define TOST_CONFIG_CPP
#include "rConfig.h"

using namespace Tost;

void* Config::_instance = NULL;

Config::Config()
{
	_instance = this;
	parseFile("config.cfg");
}

Config::Config(char *path)
{
	_instance = this;
	parseFile(path);
}

bool Config::parseFile(char *path)
{
	std::ifstream input(path);
	if(input.is_open())
	{
		std::string buffer;
		size_t limiter;
		size_t limiter_e;//dla konca przy ukladzie <string, string>

		while(!input.eof())
		{
			getline(input, buffer);
			if(buffer[0] == ';') continue;
			buffer.erase(remove_if(buffer.begin(), buffer.end(), isspace), buffer.end());//usuwa wszystkie biale znaki, centralnie wszystke nawet jesli to ma byc string, poprawic potem
			limiter = buffer.find_first_of('=');
			
			if(limiter != std::string::npos)
			{
				if(buffer[limiter+1]=='"')
				{
					//<string, string>
					limiter_e = buffer.find_last_of('"');
					this->_strings[buffer.substr(0, limiter)] = buffer.substr(limiter+2, limiter_e-(limiter+2));
				}
				else
				{
					//<string, int>
					int value;

					std::istringstream iss(buffer.substr(limiter+1));//zamiana stringa na inta taka troche malo elegancka
					iss >> value;
					_ints[buffer.substr(0, limiter)] = value;
					//buffer.clear();
				}
			}
		}
	}
	else
	{
		throw new Tost::Error(1, "File doesen't exist");
	}
}

Config* Config::getInstance()
{
	if(_instance == NULL)
	{
		return new Config();
	}
	else
	{
		return (Config*)_instance;
	}
}

void Config::printAll()
{
	if(_ints.empty() != true)
	{
		for( std::map<std::string, int>::iterator ii=_ints.begin(); ii!=_ints.end(); ii++)
		{
			std::cout << (*ii).first.c_str() << ": " << (*ii).second << std::endl;
		}
	}
	std::cout << std::endl;
	if(_strings.empty() != true)
	{
		for( std::map<std::string, std::string>::iterator ii=_strings.begin(); ii!=_strings.end(); ii++)
		{
			std::cout << (*ii).first.c_str() << ": " << (*ii).second.c_str() << std::endl;
		}
	}
}

int Config::getInt(char* index)
{
	return Config::getInstance()->_getInt(index);
}

int Config::_getInt(char* index)
{
	if(_ints.find(index) != _ints.end())
	{
		return _ints.find(index)->second;
	}
	else
	{
		throw new Tost::Error(2, "Missing config line");
		return 0;
	}
}

std::string Config::getString(char* index)
{
	return Config::getInstance()->_getString(index);
}


std::string Config::_getString(char* index)
{
	std::string test = index;
	if(_strings.find(test) != _strings.end())
	{
		return _strings.find(index)->second;
	}
	else
	{
		throw new Tost::Error(2, "Missing config line");
		return "";
	}
}
#endif